Course Schedule

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

For example:

  1. 2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

  1. 2, [[1,0],[0,1]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

Note:

The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

Hints:

  1. This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
  2. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
  3. Topological sort could also be done via BFS.

Solution:

  1. public class Solution {
  2. public boolean canFinish(int numCourses, int[][] prerequisites) {
  3. List<List<Integer>> adjList = new ArrayList<List<Integer>>(numCourses);
  4. for (int i = 0; i < numCourses; i++)
  5. adjList.add(i, new ArrayList<Integer>());
  6. for (int i = 0; i < prerequisites.length; i++)
  7. adjList.get(prerequisites[i][0]).add(prerequisites[i][1]);
  8. boolean[] visited = new boolean[numCourses];
  9. for (int u = 0; u < numCourses; u++)
  10. if (hasCycle(adjList, u, visited, new boolean[numCourses]))
  11. return false;
  12. return true;
  13. }
  14. boolean hasCycle(List<List<Integer>> adjList, int u, boolean[] visited, boolean[] stack) {
  15. if (visited[u])
  16. return false;
  17. if (stack[u])
  18. return true;
  19. stack[u] = true;
  20. for (Integer v : adjList.get(u))
  21. if (hasCycle(adjList, v, visited, stack))
  22. return true;
  23. visited[u] = true;
  24. return false;
  25. }
  26. }